package com.freewater.springboot.demo.spel.collection;

import com.freewater.springboot.demo.spel.Inventor;
import com.freewater.springboot.demo.spel.PlaceOfBirth;
import com.freewater.springboot.demo.spel.Society;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.SimpleEvaluationContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Society societyContext = new Society();
        Inventor inventor = new Inventor("zhangsan", "Serbian");
        inventor.setPlaceOfBirth(new PlaceOfBirth("New York", "America"));

        societyContext.getMembers().add(inventor);
        inventor = new Inventor("list", "China");
        inventor.setPlaceOfBirth(new PlaceOfBirth("Chengdu", "China"));
        societyContext.getMembers().add(inventor);

        ExpressionParser parser = new SpelExpressionParser();
        // 过滤
        List<Inventor> list = (List<Inventor>) parser.parseExpression("members.?[nationality == 'Serbian']").getValue(societyContext);
        System.out.println(list);

        Map<String, Integer> map = new HashMap<>();
        map.put("a", 12);
        map.put("b", 13);
        map.put("c", 28);
        map.put("d", 30);

        // map 过滤
        EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
        context.setVariable("map", map);
        // 等同于"#map.?[#this.value > 27]"
        Map<String, Integer> mapFiltered = (Map<String, Integer>) parser.parseExpression("#map.?[value > 27]").getValue(context);
        System.out.println(mapFiltered);

        // first
        mapFiltered = (Map<String, Integer>) parser.parseExpression("#map.^[value > 27]").getValue(context);
        System.out.println(mapFiltered);

        // last
        mapFiltered = (Map<String, Integer>) parser.parseExpression("#map.$[value > 27]").getValue(context);
        System.out.println(mapFiltered);

        // 投影（Projection）
        final List<String> cities = (List<String>) parser.parseExpression("members.![placeOfBirth.city]").getValue(societyContext);
        System.out.println(cities);
    }
}
